package com.kay.server;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * @Description: 静态资源工具类
 * @Author: Kay
 * @CreateDate: 2021/8/3$ 10:37$
 * @UpdateUser: Kay
 * @UpdateDate: 2021/8/3$ 10:37$
 */
public class StaticResourcesUtil {

    /**
     * 根据path，获取磁盘绝对路径
     *
     * @param path
     * @return
     */
    public static String getAbsolutePath(String path) {
        String classPath = StaticResourcesUtil.class.getResource("/").getPath();
        return classPath + path;
    }

    /**
     * 将 文件对应的 InputStream 通过 OutputStream 输出
     *
     * @param inputStream
     * @param outputStream
     */
    public static void outputStaticResource(InputStream inputStream, OutputStream outputStream) throws IOException {
        int totalSize = 0; // 所有长度
        while (totalSize == 0) {
            totalSize = inputStream.available();
        }
        // 先将头信息写出
        outputStream.write(HttpProtocolUtils.getHeader200(totalSize).getBytes());
        int byteSize = 1024; // 计划每次读取长度
        long writeSize = 0; // 已读长度
        byte[] bytes = new byte[byteSize];
        while (writeSize < totalSize) {
            if (writeSize + byteSize > totalSize) { // 已读 + 当前读取 > 所有
                byteSize = (int) (totalSize - writeSize);
                bytes = new byte[byteSize];
            }
            inputStream.read(bytes);
            outputStream.write(bytes);
            outputStream.flush();

            writeSize += byteSize;
        }
    }
}
